﻿using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;
using SqlSugar;

namespace SIMS.SqlSugarWebApi.Services
{
    public class StudentService : BaseService<Student>, IStudentService
    {
        private DataContext _context;

        public StudentService(DataContext context) : base(context)
        {
            _context = context;
        }

        public async Task<PagingModel<Student>> GetStudents(string no, string name, int pageNum, int pageSize)
        {
            ISugarQueryable<Student> students;
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(no))
            {
                students = _context.db.Queryable<Student>().Where(r => r.Name.Contains(name) && r.No.Contains(no)).OrderBy(r => r.Id);
            }
            else if (!string.IsNullOrEmpty(name))
            {
                students = _context.db.Queryable<Student>().Where(r => r.Name.Contains(name)).OrderBy(r => r.Id);
            }
            else if (!string.IsNullOrEmpty(no))
            {
                students = _context.db.Queryable<Student>().Where(r => r.No.Contains(no)).OrderBy(r => r.Id);
            }
            else
            {
                students = _context.db.Queryable<Student>().OrderBy(r => r.Id);
            }
            int count = await students.CountAsync();
           
            List<Student> items;
            if (pageSize > 0)
            {
                items = await students.ToPageListAsync(pageNum, pageSize);
            }
            else
            {
                items = await students.ToListAsync();
            }
            return new PagingModel<Student>()
            {
                Count = count,
                Items = items
            };
        }

        public async Task<PagingModel<Student>> GetStudentsByClasses(int classId)
        {
            var students = _context.db.Queryable<Student>().Where(r => r.ClassesId == classId).OrderBy(r => r.Id);
            int count = await students.CountAsync();
            var items = await students.ToListAsync();
            return new PagingModel<Student>()
            {
                Count = count,
                Items = items
            };
        }
    }
}
